/**
 * @description account 服务层
 * @author LI
 */

const { GoodsPhoto, GoodsInfo, Product } = require('../db/model/index')
const { formatMoreTime } = require('../utils/dateTime')

/**
 * 创建商品图片信息
 * @param {number} goodsInfoId 商品信息 id
 * @param {string} photoName 图片名称
 * @param {string} photoUrl 图片地址
 */
async function createGoodPhoto({ goodsInfoId, photoName, photoUrl }) {
  const result = await GoodsPhoto.create({
    goodsInfoId,
    photoName,
    photoUrl,
  })

  return result
}

/**
 * 获取全部商品图片信息
 * @param {string} goodsInfoId 商品信息 id
 * @param {number} page 第几页
 * @param {number} limit 多少条
 */
async function getGoodPhotosList({ id, page = 1, limit = 10 }) {
  // 拼接查询条件
  const whereData = {}
  if (id) {
    whereData.id = id
  }

  const result = await GoodsPhoto.findAndCountAll({
    limit: limit, // 每页多少条
    offset: limit * (page - 1), // 跳过多少条
    include: [
      {
        model: GoodsInfo,
        attributes: ['goodType', 'goodSn'],
        where: whereData
      }
    ]
  })
  result.rows.map(item => {
    // 格式化时间 多个
    item.dataValues = formatMoreTime(item.dataValues)
    item.dataValues.goodSn = item.dataValues.goodsInfo.goodSn
    item.dataValues.goodType = item.dataValues.goodsInfo.goodType
    delete item.dataValues.goodsInfo
  })

  return result
}

/**
 * 通过 id 更新商品图片信息
 * @param {number} id id
 * @param {string} photoName 图片名称
 * @param {string} photoUrl 图片地址
 */
async function updateGoodPhotoById({ id, photoName, photoUrl }) {
  // 拼接修改内容
  const updateData = {}
  if (photoName) {
    updateData.photoName = photoName
  }
  if (photoUrl) {
    updateData.photoUrl = photoUrl
  }
  const result = await GoodsPhoto.update(updateData, {
    where: { id }
  })

  return result[0] > 0
}

/**
 * 通过 id 删除商品信息附带把产品一并删除
 * @param {number} id id
 */
async function deleteGoodPhotoById(id) {
  const goodsPhotos = await GoodsPhoto.findAll({
    where: { id },
    include: [{
      model: Product,
    }],
  })
  for (const goodsPhoto of goodsPhotos) {
    for (const child of goodsPhoto.products) {
      child.destroy();
    }
    goodsPhoto.destroy();
  }

  return true
}

module.exports = {
  createGoodPhoto,
  getGoodPhotosList,
  updateGoodPhotoById,
  deleteGoodPhotoById
}
